package com.example.servlet;

import com.entity.Saler;
import com.service.imp.BusinessServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "loginServlet", value = "/loginServlet")
public class loginServlet extends HttpServlet {
//    private String message;
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try{
            request.setCharacterEncoding("UTF-8");
            String accountName = request.getParameter("username");
            String password = request.getParameter("password");

            BusinessServiceImpl service = new BusinessServiceImpl();
            Long id = service.checkPassword(accountName,password);
            if(id!= 0) {
                request.setAttribute("message", "登录成功");
                Saler saler = service.getUserById(id);
                request.getSession().setAttribute("user", saler);
                Cookie sessionCookie = new Cookie("session", request.getSession().getId());
                sessionCookie.setMaxAge(60*60);
                response.addCookie(sessionCookie);
                request.getRequestDispatcher("/salerWindow.jsp").forward(request, response);
            }else{
                request.setAttribute("message", "密码验证失败");
                request.getRequestDispatcher("/message.jsp").forward(request, response);
            }
        }catch(Exception e){
            e.printStackTrace();
            request.setAttribute("message", "登录失败");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }

}